//
//  HomeWorkViewController.m
//  家校互通
//
//  Created by 李赛 on 15/5/24.
//  Copyright (c) 2015年 姬鑫宇. All rights reserved.
//

#import "HomeWorkViewController.h"
#import "HWCommentTableViewCell.h"
#import "HWHeaderTableViewCell.h"
#import "HWInfoDetailTableViewCell.h"
#import "HWPraiseTitleTableViewCell.h"
#import "UITableView+FDTemplateLayoutCell.h"

#import "HcCustomKeyboard.h"//键盘操作

#import "ImageCollectionViewCell.h"
#import "HWfooterViewReusableView.h"
#import "userHeaderImageCollectionViewCell.h"
#import "BLParaEnumParamiter.h"
#import "CommenBtnForImage.h"

#import <UIImageView+WebCache.h>
#import "HZPhotoBrowser.h"

@interface HomeWorkViewController ()<UITableViewDataSource,UITableViewDelegate,UICollectionViewDelegate,UICollectionViewDataSource,HZPhotoBrowserDelegate,ConnectControlDelegate>{
    ConnectControl *connectCtr;
    CGFloat picCellWidth;

}
@property (nonatomic, assign) BOOL cellHeightCacheEnabled;
@property (nonatomic, retain) NSMutableArray *imageListArray;
@property (nonatomic, retain) BlackBoardDetail *detail;

@property (nonatomic, retain) NSMutableArray *commentListArray;
@property (nonatomic, retain) NSMutableArray *readerListArray;
@end

@implementation HomeWorkViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    picCellWidth=(DSF_SCREENWIDTH-20)/3;
      [self initViewByData];
    connectCtr = [ConnectControl showForView:self.view];
    connectCtr.delegate=self;
    
    if (connectCtr.superview!=nil && connectCtr.loading==NO)
    {
        [connectCtr setLoading:YES];
    }
    
    // Do any additional setup after loading the view.
}

- (void)initViewByData{
    _imageListArray=[[NSMutableArray alloc]initWithCapacity:0];
    _readerListArray=[[NSMutableArray alloc]initWithCapacity:0];
    _commentListArray=[[NSMutableArray alloc]initWithCapacity:0];
    if (_viewControllerTag==BLViewControllerTagForHomeWork) {
        self.title=@"作业详情";
        
    }else if (_viewControllerTag==BLViewControllerTagForNotice)
    {
        self.title=@"通知详情";
    }else if (_viewControllerTag==BLViewControllerTagForPraise)
    {
        self.title=@"表彰详情";
    }else if (_viewControllerTag==BLViewControllerTagForActivity)
    {
        self.title=@"活动详情";
    }

    _contentTabelView.dataSource=self;
    _contentTabelView.delegate=self;
    _contentTabelView.estimatedRowHeight = 200;
    _contentTabelView.fd_debugLogEnabled = YES;
    
    self.cellHeightCacheEnabled = YES;
    [self createBottomHolderView];
    [[HcCustomKeyboard customKeyboard] textViewShowView:self customKeyboardDelegate:self];
}


- (void)connect{
    [ConnectControl removeFromView:self.view];
  

    NSInteger boardId = [_blackboardId integerValue];
    
    [CoModel getNewsDetail:^(BOOL result,BlackBoardDetail *model, NSError *error) {
        _detail = model;
        if (model.is_collect) {
            _collectBtn.selected = YES;
        }
        _imageListArray=[NSMutableArray arrayWithArray:model.images];
        _readerListArray=[NSMutableArray arrayWithArray:model.readers];
        
        [_contentTabelView reloadData];
        
        //暂时不用，getNewsDetail获取的时候有个二级列表中有评论
        
        [CoModel getComments:^(BOOL result,NSArray *array, NSError *error) {
            [ConnectControl removeFromView:self.view];
            _commentListArray =[NSMutableArray arrayWithArray:array];
            [_contentTabelView reloadData];
        } withBlackboardId:boardId withPageNumber:0 withPageSize:5];
        
        [CoModel modifyRelation:^(BOOL result, NSError *error) {
            
        } withBlackboardId:boardId withType:1 withStatus:1];
        
    } withBlackboardId:[_blackboardId integerValue] withPageNumber:0 withPageSize:5];
}

-(void)createBottomHolderView
{
    CommenBtnForImage *commentBtn=[[CommenBtnForImage alloc]initWithFrame:CGRectMake(0, 0, DSF_SCREENWIDTH-240,40) withImageString:@"写评论" TitleName:@"写评论" withImageWidth:32];
    UITapGestureRecognizer *commentBtnTap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(commentAction:)];
    [commentBtn addGestureRecognizer:commentBtnTap];
    [_holdView addSubview:commentBtn];
    
}

- (void)commentAction:(UIButton *)sender {
    
    [HcCustomKeyboard customKeyboard].placeHoldLable.text=@"我来说两句...";
    [[HcCustomKeyboard customKeyboard] talkAndReplyTextWithTypeTag:keyboardCommentTypeTalkAdd withReplyUserId:0 rootTalkId:0];
}
-(void)talkBtnClick:(UITextView *)textViewGet typeTag:(NSInteger)typeTag withReplyUserId:(NSInteger)replyUserId rootTalkId:(NSInteger)rootTalkId{
    
    [CoModel comment:^(BOOL result, NSError *error) {
        if (result) {
//            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"评论成功" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
//            [alertView show];
            [self connect];
        }
    } withBlackboardId:[_blackboardId integerValue] withReceiverId:0 withContent:textViewGet.text];
}

- (IBAction)privateChatAction:(UIButton *)sender {
     UUChatViewController *vc =[self.storyboard instantiateViewControllerWithIdentifier:@"UUChatViewController"];
    [self.navigationController pushViewController:vc animated:YES];
}
- (IBAction)shareBtnAction:(UIButton *)sender {
    
}
- (IBAction)collectionBtnAction:(UIButton *)sender {
   
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    if (sender.selected) {
        sender.selected=NO;
        [CoModel modifyRelation:^(BOOL result, NSError *error) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            if (result) {
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"取消收藏" message:nil delegate:sender cancelButtonTitle:@"确定" otherButtonTitles:nil];
                [alertView show];
                sender.selected = NO;
            }
        } withBlackboardId:[_blackboardId integerValue] withType:2 withStatus:0];
    }else{
         sender.selected=YES;
        [CoModel modifyRelation:^(BOOL result, NSError *error) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            if (result) {
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"收藏成功" message:nil delegate:sender cancelButtonTitle:@"确定" otherButtonTitles:nil];
                [alertView show];
                sender.selected = YES;
            }
        } withBlackboardId:[_blackboardId integerValue] withType:2 withStatus:1];
    }
}


#pragma mark -UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section==0) {
        return 1;
    }else if(section==1)
    {
        if (_viewControllerTag==BLViewControllerTagForPraise) {
            return 2;
        }else
            return 1;
        
    }else
        return _commentListArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==0) {
        HWHeaderTableViewCell *vCell=[tableView dequeueReusableCellWithIdentifier:@"HWHeaderTableViewCell" forIndexPath:indexPath];
        [vCell setBlackBoardModel:_detail];
        return vCell;
    }
    else if (indexPath.section==1)
    {
        if (_viewControllerTag==BLViewControllerTagForPraise)
        {
            if(indexPath.row==0)
            {
                HWPraiseTitleTableViewCell *vCell=[tableView dequeueReusableCellWithIdentifier:@"HWPraiseTitleTableViewCell" forIndexPath:indexPath];
                vCell.iconImage.image=[UIImage imageNamed:@"被表彰的人"];
                vCell.titleLB.text=_detail.student_name;
                return vCell;
            }
            else
            {
               HWInfoDetailTableViewCell *vCell=[tableView dequeueReusableCellWithIdentifier:@"HWInfoDetailTableViewCell" forIndexPath:indexPath];
                [vCell setBlackBoardDetail:_detail];
               [vCell setCollectionViewDataSourceDelegate:self contentIndex:collectionViewTagForContentMImage userImageIndex:collectionViewTagForUserHeaderImage];
                return vCell;
            }

        }else
        {
            HWInfoDetailTableViewCell *vCell=[tableView dequeueReusableCellWithIdentifier:@"HWInfoDetailTableViewCell" forIndexPath:indexPath];
            [vCell setBlackBoardDetail:_detail];
           [vCell setCollectionViewDataSourceDelegate:self contentIndex:collectionViewTagForContentMImage userImageIndex:collectionViewTagForUserHeaderImage];
         
            return vCell;
        }
        
    }
    else
    {
        ContentModel *model = [_commentListArray objectAtIndex:indexPath.row];
        
        HWCommentTableViewCell *vCell=[tableView dequeueReusableCellWithIdentifier:@"HWCommentTableViewCell" forIndexPath:indexPath];
//        if(indexPath.row%2)
//        {
//            [vCell setTextWithcontentStr:model.content withCommentName:model.sender_nickname replyName:model.receiver_nickname];
//        }else
//        {
//            [vCell setTextWithcontentStr:@"和我们平时说的字体不同，计算机意义上的字体表示的是同一大小，同一样式(Style)字形的集合。从这个意义上来说，当我们为文字设置粗体，斜体时其实是使用了另外一种字体(下划线不算)" withCommentName:@"小明（父亲）" replyName:@"王老师"];
//        }
        [vCell setTextWithcontentStr:model.content withCommentName:model.sender_nickname replyName:model.receiver_nickname];

        return vCell;
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return nil;
}
#pragma mark -UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==0) {
            return 60;
    }
    else if (indexPath.section==1)
    {
        if (_viewControllerTag==BLViewControllerTagForPraise) {
            if(indexPath.row==0)
            {
                return 45;
            }
            else
            {
            
                CGSize sizeToFit=[_detail.content sizeWithFont:[UIFont systemFontOfSize:15] maxSize:CGSizeMake(DSF_SCREENWIDTH-16, MAXFLOAT)];
                 NSInteger indexRow=_imageListArray.count%3?_imageListArray.count/3+1:_imageListArray.count/3;//每行三张图，一共几行
                if (_imageListArray.count)
                {
                     return 10+picCellWidth*indexRow+5*(indexRow-1)+40+35+sizeToFit.height;
                }else
                {
                    return 10+40+35+sizeToFit.height;
                }
               
            }

        }else
        {

            CGSize sizeToFit=[_detail.content sizeWithFont:[UIFont systemFontOfSize:15] maxSize:CGSizeMake(DSF_SCREENWIDTH-16, MAXFLOAT)];
         
            NSInteger indexRow=_imageListArray.count%3?_imageListArray.count/3+1:_imageListArray.count/3;
            
            if (_imageListArray.count) {
                return 10+picCellWidth*indexRow+5*(indexRow-1)+40+35+sizeToFit.height;
            }else
            {
                return 10+40+35+sizeToFit.height;
            }
    
        }

      
    }
    else
    {
        ContentModel *model = [_commentListArray objectAtIndex:indexPath.row];
        
        return [tableView fd_heightForCellWithIdentifier:@"HWCommentTableViewCell" cacheByIndexPath:indexPath configuration:^(HWCommentTableViewCell *vCell) {
            //                if(indexPath.row%2)
            //                {
            //                    [vCell setTextWithcontentStr:@"CocoaChina是全球最大的苹果开发中文社区，官方微信每日定时推送各种精彩的研发教程资源和工具" withCommentName:@"小明（父亲）" replyName:nil];
            //                }else
            //                {
            //                    [vCell setTextWithcontentStr:@"和我们平时说的字体不同，计算机意义上的字体表示的是同一大小，同一样式(Style)字形的集合。从这个意义上来说，当我们为文字设置粗体，斜体时其实是使用了另外一种字体(下划线不算)" withCommentName:@"小明（父亲）" replyName:@"王老师"];
            //                }
            [vCell setTextWithcontentStr:model.content withCommentName:model.sender_nickname replyName:model.receiver_nickname];
        }];
        
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.001;
}
// Called after the user changes the selection.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
}


#pragma mark---UICollectionViewDataSource--
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (collectionView.tag==collectionViewTagForContentMImage){
        
       return  CGSizeMake(picCellWidth, picCellWidth);
    }else
        return CGSizeMake(25, 25);
   
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (collectionView.tag==collectionViewTagForContentMImage) {
        return _imageListArray.count;
    }else
        return _readerListArray.count;//读者数量
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (collectionView.tag==collectionViewTagForContentMImage)
    {
        ImageCollectionViewCell *vCell=[collectionView dequeueReusableCellWithReuseIdentifier:@"ImageCollectionViewCell" forIndexPath:indexPath];
        [vCell.activityImage sd_setImageWithURL:[NSURL URLWithString:[_imageListArray objectAtIndex:indexPath.row]] placeholderImage:[UIImage imageNamed:@"icon01.jpg"]];
        return vCell;
    }else
    {
        userHeaderImageCollectionViewCell *vCell=[collectionView dequeueReusableCellWithReuseIdentifier:@"userHeaderImageCollectionViewCell" forIndexPath:indexPath];
        ReaderListModel *model=[_readerListArray objectAtIndex:indexPath.row];
        [vCell.userHeaderImage sd_setImageWithURL:[NSURL URLWithString:model.icon] placeholderImage:[UIImage imageNamed:@"icon01.jpg"]];
        return vCell;
    }
    
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if (collectionView.tag==collectionViewTagForUserHeaderImage) {
        HWfooterViewReusableView *footerView=[collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"HWfooterViewReusableView" forIndexPath:indexPath];
        if (_detail.read_count) {
             footerView.footerTitleLB.text=[NSString stringWithFormat:@"已读 %@",@(_detail.read_count)];
        }
       
        return footerView;
    }
    return nil;
}
#pragma mark---UICollectionViewDelegate--
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (collectionView.tag==collectionViewTagForContentMImage)
    {
       

        HZPhotoBrowser *browserVc = [[HZPhotoBrowser alloc] init];
        browserVc.sourceImagesContainerView = collectionView; // 原图的父控件
        browserVc.imageCount =_imageListArray.count; // 图片总数
        browserVc.currentImageIndex = indexPath.row;
        browserVc.delegate = self;
        
        [self.view.window.rootViewController presentViewController:browserVc animated:NO completion:nil];
   
    }else
    {
        
    }
}


// 2.实现代理方法

// 返回临时占位图片（即原来的小图）
-(UIImage *)photoBrowser:(HZPhotoBrowser *)browser placeholderImageForIndex:(NSInteger)index
{
    UIImageView *imageView=[[UIImageView alloc]init];
    [imageView sd_setImageWithURL:[NSURL URLWithString:[_imageListArray objectAtIndex:index]] placeholderImage:[UIImage imageNamed:@"icon01.jpg"]];;
    return imageView.image;
}

// 返回高质量图片的url
-(NSURL *)photoBrowser:(HZPhotoBrowser *)browser highQualityImageURLForIndex:(NSInteger)index
{
    NSString *urlStr = [[_imageListArray objectAtIndex:index] stringByReplacingOccurrencesOfString:@"thumbnail" withString:@"bmiddle"];
    return [NSURL URLWithString:urlStr];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
